<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.usernameKeyword" placeholder="用户名" style="width: 130px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.type" placeholder="网关账号类型" filterable clearable style="width: 140px; margin-left: 10px;" class="filter-item">
        <el-option v-for="item in gatewayAccountTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.status" placeholder="状态" filterable clearable style="width: 140px; margin-left: 10px;" class="filter-item">
        <el-option v-for="item in gatewayAccountStatusOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="info" icon="el-icon-refresh" @click="handleRefresh">
        重置
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="info" icon="el-icon-circle-plus-outline" @click="handleAdd">
        添加
      </el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" :header-cell-style="headerCellStyle" border stripe element-loading-text="拼命加载中">
      <el-table-column label="用户名" align="center" width="230px">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="密码" align="center" width="230px">
        <template slot-scope="{row}">
          <span>{{ row.password }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" min-width="110px">
        <template slot-scope="{row}">
          <span style="float: left;">{{ row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="网关账号类型" align="center" width="110px">
        <template slot-scope="{row}">
          <span>{{ row.type | typeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="50px">
        <template slot-scope="{row}">
          <span>{{ row.status | statusFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <router-link :to="'/system/gateway-account-detail/'+scope.row.id">
            <el-button type="primary" size="mini" icon="el-icon-edit">
              详情
            </el-button>
          </router-link>
          <el-button type="danger" size="mini" style="margin-left: 5px;" icon="el-icon-delete" @click="handleDelete(scope)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog title="账号添加" :visible.sync="accountAddVisible">
      <el-form ref="accountAddForm" :rules="accountAddRules" :model="accountAdd" label-width="110px" style="width: 600px; margin-left:0px;">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="accountAdd.username" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="accountAdd.password" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="网关账号类型" prop="type">
          <el-select v-model="accountAdd.type" filterable placeholder="请选择">
            <el-option v-for="item in gatewayAccountTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="accountAdd.status" filterable placeholder="请选择">
            <el-option v-for="item in gatewayAccountStatusOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="accountAdd.remark" type="textarea" :rows="2" style="width: 300px;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="accountAddVisible = false">取消</el-button>
        <el-button type="primary" @click="addConfirm()">确认</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { Message } from 'element-ui'
import { fetchEnum, getGatewayAccountByPage, addGatewayAccount, deleteGatewayAccountById } from '@/api/system-api'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import { toOptionsList, toKeyValueMap } from '@/utils/index'

var gatewayAccountTypeKeyValue = {}
var gatewayAccountStatusKeyValue = {}

export default {
  name: 'SystemGatewayAccountList',
  components: { Pagination },
  directives: { waves },
  filters: {
    typeFilter(type) {
      return gatewayAccountTypeKeyValue[type]
    },
    statusFilter(status) {
      return gatewayAccountStatusKeyValue[status]
    }
  },
  data() {
    return {
      beforeRouteEnterNextIgnore: true,

      gatewayAccountTypeOptions: [],
      gatewayAccountStatusOptions: [],
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        usernameKeyword: null,
        type: null,
        status: null
      },

      listLoading: true,
      list: null,
      total: 0,

      accountAddVisible: false,
      accountAdd: {
        username: null,
        password: null,
        type: null,
        status: null,
        remark: null
      },
      accountAddRules: {
        username: [{
          required: true, message: '请输入用户名', trigger: 'blur'
        }],
        password: [{
          required: true, message: '请输入密码', trigger: 'blur'
        }],
        type: [{
          required: true, message: '请输入网关账号类型', trigger: 'blur'
        }],
        status: [{
          required: true, message: '请输入状态', trigger: 'blur'
        }]
      }

    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (!vm.beforeRouteEnterNextIgnore) {
        vm.getList()
      } else {
        vm.beforeRouteEnterNextIgnore = false
      }
    })
  },
  async created() {
    await this.initLoad()
    await this.getList()
  },
  methods: {
    async initLoad() {
      const enumCodes = ['GATEWAY_ACCOUNT_STATUS', 'GATEWAY_ACCOUNT_TYPE']
      const { data } = await fetchEnum(enumCodes)
      for (const item of data) {
        if (item.code === 'GATEWAY_ACCOUNT_STATUS') {
          if (item.options) {
            this.gatewayAccountStatusOptions = toOptionsList(item.options, 'code', 'name')
            gatewayAccountStatusKeyValue = toKeyValueMap(this.gatewayAccountStatusOptions, 'key', 'display_name')
          }
        } else if (item.code === 'GATEWAY_ACCOUNT_TYPE') {
          if (item.options) {
            this.gatewayAccountTypeOptions = toOptionsList(item.options, 'code', 'name')
            gatewayAccountTypeKeyValue = toKeyValueMap(this.gatewayAccountTypeOptions, 'key', 'display_name')
          }
        }
      }
      this.initListQuery()
    },
    getList() {
      this.listLoading = true
      getGatewayAccountByPage(this.listQuery).then(response => {
        const { data } = response
        this.list = data.result
        this.total = data.totalCount
        setTimeout(() => {
          this.listLoading = false
        }, 1 * 1000)
      })
    },
    initListQuery() {
      this.listQuery = {
        pageNo: 1,
        pageSize: 20,
        usernameKeyword: null,
        type: null,
        status: null
      }
    },

    handleFilter() {
      this.getList()
    },
    handleRefresh() {
      this.initListQuery()
      this.getList()
    },
    handleAdd() {
      this.accountAdd = {
        username: null,
        password: null,
        type: null,
        status: null,
        remark: null
      }
      this.accountAddVisible = true
    },
    headerCellStyle({ row, rowIndex }) {
      return 'background-color: #42b983; color: #FFF;'
    },

    addConfirm() {
      this.$refs.accountAddForm.validate((valid) => {
        if (!valid) {
          return
        }
        var data = JSON.parse(JSON.stringify(this.accountAdd))
        addGatewayAccount(data).then(response => {
          this.$notify({
            title: '成功',
            message: '添加成功',
            type: 'success',
            duration: 2000
          })
          this.accountAddVisible = false
          this.getList()
        }).catch(error => {
          Message({
            message: error,
            type: 'error',
            duration: 5 * 1000
          })
        })
      })
    },
    handleDelete(accountScope) {
      deleteGatewayAccountById(accountScope.row.id).then(response => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      }).catch(error => {
        Message({
          message: error,
          type: 'error',
          duration: 5 * 1000
        })
      })
    }

  }
}

</script>
